#!/usr/bin/env python
import pygame
from pygame.locals import *
from optparse import OptionParser
import cPickle
import pylab, scipy, os
from utils import *

parser = OptionParser()
parser.add_option("--fresh",action="store_true",dest="fresh",default=False,help="overwrite the existing training examples. By default, these examples will be appended")
(opts,args) = parser.parse_args()
letter = args[0]
dump_file = "mystery.pickle" if letter == "mystery" else os.path.join("john-chars",letter+".pickle")
all_strokes = [] if opts.fresh or not os.path.exists(dump_file) else load(dump_file)

strokes = []
stroke = []
bg = pygame.image.load('bg.png')
TFwriting = False

class Gooey:
   
    def __init__(self):
        # Initialize PyGame
        global bg
        pygame.init()
        icon = pygame.image.load('icon.jpg')
        pygame.display.set_icon(icon)
        pygame.display.set_caption('WYOMING')
        self.screen = pygame.display.set_mode((800,600))
        self.screen.blit(bg, (0,0))
 
    def run(self):
        # Update display initially
        pygame.display.update()
        # Run the event loop
        self.loop()
        # Close the Pygame window
        pygame.quit()
    
    def loop(self):
        clock = pygame.time.Clock()
        exit = False
        while not exit:
            clock.tick(100)
            # Handle input events
            exit = self.handleEvents()
            # Wait a little?
            #pygame.time.delay(1)
 
    def handleEvents(self):
        global stroke, strokes, bg, TFwriting
        DIMeraser = [[85, 50], [85+35, 49+30]]
        DIMequals = [[60, 470], [60+50, 470+30]]
        DIMwriting = [[120, 50], [120+670, 50+260]]
        POScursor = pygame.mouse.get_pos()
        b1,b2,b3 = pygame.mouse.get_pressed()
        exit = False
        for event in pygame.event.get():
            if event.type == QUIT:
                exit = True
            elif event.type == KEYDOWN:
                # Quit
                if event.key == K_ESCAPE:
                    exit = True
                # Convert to LaTex  
                elif event.key == K_RETURN:
                    self.latexIt()
            elif event.type == MOUSEBUTTONDOWN:
                # Start stroke
                if self.inRange(POScursor, DIMwriting):
                    self.paintCircle(POScursor)
                    stroke.append(POScursor)
                    TFwriting = True
                # Erase last stroke
                elif self.inRange(POScursor, DIMeraser):
                    self.eraseStroke()
                # Convert to LaTex
                elif self.inRange(POScursor, DIMequals):
                    self.latexIt()
            elif event.type == MOUSEMOTION:
                #POScursor = pygame.mouse.get_pos()
                #b1,b2,b3 = pygame.mouse.get_pressed()
                if b1 == True & TFwriting == True:
                    # Continue stroke 
                    if self.inRange(POScursor, DIMwriting):
                        self.paintCircle(POScursor)
                        stroke_point = (POScursor[0], POScursor[1])
                        stroke.append(stroke_point);
                    # Stop and erase stroke
                    else:
                        strokes.append(stroke)
                        stroke = []
                        TFwriting = False
                        self.eraseStroke()
            elif event.type == MOUSEBUTTONUP:
                # Add stroke to stroke list
                if TFwriting == True:
                    if len(stroke) > 1:
                        stroke = stroke[1:]
                    strokes.append(stroke)
                    stroke = []
                    TFwriting = False
        return exit
            
    def inRange(self, pos, box):
        return box[0][0] <= pos[0] and pos[0] <= box[1][0] and \
            box[0][1] <= pos[1] and pos[1] <= box[1][1]
    
    def paintCircle(self, pos):
        pygame.draw.circle(self.screen,(0,0,0),pos,2,2)
        pygame.display.update()
    
    def eraseStroke(self):
        global strokes, bg
        if len(strokes) >= 1:
            self.screen.blit(bg, (0,0))
            strokes.pop()
            for s in strokes:
                for pos in s:
                    pygame.draw.circle(self.screen,(0,0,0),pos,2,2)
            pygame.display.update()

    def latexIt(self):
        global strokes, bg
        all_strokes.append(strokes)        
        with open(dump_file,"w") as fd: cPickle.dump(all_strokes,fd)
        strokes = []
        self.screen.blit(bg, (0,0))
        pygame.display.update()

# Start the game
Gooey().run()
